﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CMSLibrary.TagsCreate.CustomFunction.Common
{
    /// <summary>
    /// 截取字符串
    /// 1.  Substring(源文本, 起始位置)
    /// 2.  Substring(源文本, 起始位置, 截取长度)
    /// </summary>
    public class Custom_Substring : PFunctionBase
    {
        #region 参数成员
        /// <summary>
        /// 源文本
        /// </summary>        
        string source = string.Empty;        
        /// <summary>
        /// 起始字符位置
        /// </summary>        
        int startIndex = 0;        
        /// <summary>
        /// 截取长度
        /// </summary>
        int length = 0;        
        #endregion

        #region 重写的方法
        protected override void SplitFormatParas(string sourceParas)
        {
            string[] paras = GetParasArray(sourceParas);
            //确定重载方法,由多到少
            /********** 2 **********/
            try
            {
                source = GetUnitString(paras, paras.GetUpperBound(0) - 1);
                startIndex = Convert.ToInt32(paras[paras.GetUpperBound(0) - 1]);
                length = Convert.ToInt32(paras[paras.GetUpperBound(0)]);
                FunctionBurden = BurdenIndex.two;
                return;
            }
            catch{}
            /********** 1 **********/
            try
            {
                source = GetUnitString(paras, paras.GetUpperBound(0));
                startIndex = Convert.ToInt32(paras[paras.GetUpperBound(0)]);
                FunctionBurden = BurdenIndex.one;
                return;
            }
            catch { throw new Exception(); }
        }

        public override string ToString()
        {
            string result = string.Empty;
            //验证参数
            if (source != string.Empty)
            {
                if(startIndex >= source.Length){ startIndex = source.Length - 1; }
                if ((startIndex + length) > source.Length) { length = source.Length - startIndex; }

                switch (FunctionBurden)
                {
                    case BurdenIndex.one:
                        result = source.Substring(startIndex);
                        break;
                    case BurdenIndex.two:
                        result = source.Substring(startIndex, length);
                        break;
                }
            }
            return result;
        }
        #endregion

        #region 私有方法
        protected string GetUnitString(string[] paras, int MaxIndex)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paras.Length; i++ )
            {
                if (i < MaxIndex)
                {
                    sb.Append(paras[i]).Append(
                        (i == MaxIndex - 1) ? string.Empty : ","
                        );
                }
            }
            return sb.ToString();
        }
        #endregion
    }
}
